package com.example.administrator.application;

/**
 * Created by Administrator on 2016/11/19.
 */
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContentPreActivity extends AppCompatActivity {


    ListView listView;
    final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_pre);

        listView=(ListView)findViewById(R.id.listView);
    }
    @TargetApi(Build.VERSION_CODES.M)
    public void showPeople(View view){
        int hasSendSmsPermission = ActivityCompat.checkSelfPermission(ContentPreActivity.this, Manifest.permission.READ_CONTACTS);
        if (hasSendSmsPermission != PackageManager.PERMISSION_GRANTED) {
            if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                showMessageOKCancel("你需要授权通讯录权限",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(ContentPreActivity.this, new String[] {Manifest.permission.READ_CONTACTS},
                                        REQUEST_CODE_ASK_PERMISSIONS);
                            }
                        });
            }
            else {
                ActivityCompat.requestPermissions(ContentPreActivity.this,new String[]{Manifest.permission.READ_CONTACTS},
                        REQUEST_CODE_ASK_PERMISSIONS);

            }

        }
        else{
            ContentResolver contentResolver=ContentPreActivity.this.getContentResolver();
            Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
            List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
            while (cursor.moveToNext()){
                int inIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                int id = cursor.getInt(inIndex);
                int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                String displayName = cursor.getString(nameIndex);
                Cursor phone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                        ,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id,null,null);
                String phoneNumber=null;
                while (phone.moveToNext()){
                    int phoneNumberIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    phoneNumber = phone.getString(phoneNumberIndex);
                }
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("id",id);
                item.put("name",displayName);
                item.put("phoneNumber",phoneNumber);
                items.add(item);

            }

            SimpleAdapter adapter=new SimpleAdapter(ContentPreActivity.this,
                    items,
                    R.layout.layout_list_item,
                    new String[]{"id","name","phoneNumber"},
                    new int[] {R.id.tetId,R.id.tetName,R.id.tetPhone}
            );
            listView.setAdapter(adapter);

        }


    }
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(ContentPreActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    ContentResolver contentResolver=ContentPreActivity.this.getContentResolver();
                    Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
                    List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
                    while (cursor.moveToNext()){
                        int inIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                        int id = cursor.getInt(inIndex);
                        int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                        String displayName = cursor.getString(nameIndex);
                        Cursor phone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                                ,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id,null,null);
                        String phoneNumber=null;
                        while (phone.moveToNext()){
                            int phoneNumberIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                            phoneNumber = phone.getString(phoneNumberIndex);
                        }
                        Map<String, Object> item = new HashMap<String, Object>();
                        item.put("id",id);
                        item.put("name",displayName);
                        item.put("phoneNumber",phoneNumber);
                        items.add(item);
                    }
                    SimpleAdapter adapter=new SimpleAdapter(ContentPreActivity.this,
                            items,
                            R.layout.layout_list_item,
                            new String[]{"id","name","phoneNumber"},
                            new int[] {R.id.tetId,R.id.tetName,R.id.tetPhone}
                    );
                    listView.setAdapter(adapter);
                } else {
                    // Permission Denied
                    Toast.makeText(ContentPreActivity.this, "GET_Contact Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

}
